package com.heatup.apt.api.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.heatup.apt.common.constants.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.common.exception.OrderException;
import com.heatup.apt.api.service.OrderService;
import com.heatup.apt.api.service.TemplateSendService;
import com.heatup.apt.common.constants.OrderContants.OrderType;
import com.heatup.apt.common.constants.ServiceConstans.ServiceType;
import com.heatup.apt.common.dao.CompanyStaffConsumeMapper;
import com.heatup.apt.common.dao.CompanyStaffMapper;
import com.heatup.apt.common.dao.CourseInfoMapper;
import com.heatup.apt.common.dao.CourseScheduleMapper;
import com.heatup.apt.common.dao.OrderDetailMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.OrderInfoResultMapper;
import com.heatup.apt.common.dao.ProductServiceDetailMapper;
import com.heatup.apt.common.dao.ServicePriceMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.dao.user.UserAccountConsumeMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.dao.user.UserProductServiceMapper;
import com.heatup.apt.common.util.DateUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.model.api.OrderBookTypeModel;
import com.heatup.apt.model.api.OrderInfoResultModel;
import com.heatup.apt.model.api.ServicePriceResultModel;
import com.heatup.apt.model.company.CompanyStaff;
import com.heatup.apt.model.company.CompanyStaffConsume;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.course.CourseInfoModel;
import com.heatup.apt.model.course.CourseSchedule;
import com.heatup.apt.model.order.OrderDetail;
import com.heatup.apt.model.order.OrderFinished;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.order.OrderRefund;
import com.heatup.apt.model.product.ProductServiceDetail;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.user.UserAccountConsume;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserProductService;
import com.heatup.apt.model.vo.CasherResolveLog;
import com.heatup.apt.model.vo.MealListVO;

/**
 * 产品价格服务
 * 
 * @author Jindaodaxia
 *
 */
@Service
public class OrderServiceImpl extends SuperServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {

	private Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

	@Resource
	private OrderDetailMapper orderDetailMapper;

	@Resource
	private OrderInfoMapper orderInfoMapper;

	@Resource
	private ServicePriceMapper servicePriceMapper;

	@Resource
	private CourseScheduleMapper courseScheduleMapper;

	@Resource
	private CourseInfoMapper courseInfoMapper;

	@Resource
	private UserInfoMapper userInfoMapper;

	@Resource
	private TemplateSendService templateSendService;

	@Resource
	private OrderInfoResultMapper orderInfoResultMapper;

	@Resource
	private UserAccountConsumeMapper userAccountConsumeMapper;

	@Resource
	private CompanyStaffConsumeMapper companyStaffConsumeMapper;

	@Resource
	private CompanyStaffMapper companyStaffMapper;

	@Resource
	private UserProductServiceMapper userProductServiceMapper;
	
	@Resource
	private ProductServiceDetailMapper productServiceDetailMapper;

	@Resource
	private StoreInfoMapper storeInfoMapper;

	@Override
	public OrderInfo getOrderById(int orderId) {
		return orderInfoMapper.selectById(orderId);
	}

	@Override
	public Map<String, Object> getOrderInfo(int orderId) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		OrderInfo orderInfo = getOrderById(orderId);
		if (orderInfo == null) {
			throw new Exception("订单不存在");
		}

		map.put("orderId", orderInfo.getId());
		map.put("totalPrice", orderInfo.getAmount());
		map.put("orderStatus", orderInfo.getOrderStatus());
		map.put("payStatus", orderInfo.getPayStatus());
		map.put("payType", orderInfo.getPayType() == 2 ? 2 : 1);
		ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(orderInfo.getServiceId());
		if (servicePrice == null) {
			throw new Exception("订单错误");
		}
		map.put("serviceName", servicePrice.getServiceName());
		map.put("courseId", servicePrice.getCourseId());

		OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderId);

		// 自助健身用到店时间
		if (orderInfo.getOrderType() == OrderType.selffit.getIndex()) {
			if (orderDetail != null) {
				String time = DateUtils.format(orderDetail.getStartTime(), DateUtils.datePatternChinese) + " "
						+ DateUtils.format(orderDetail.getStartTime(), DateUtils.shortTimePattern);
				map.put("orderTime", time);
			}
		} else {
			// 上课时间查课程表
//			CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//			courseScheduleExample.or().andCourseIdEqualTo(servicePrice.getCourseId());
//			List<CourseSchedule> scheduleList = courseScheduleMapper.selectByExample(courseScheduleExample);

            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(servicePrice.getCourseId());
            EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(entityWrapper);
			CourseSchedule courseSchedule = null;
			if (scheduleList.size() > 0) {
				courseSchedule = scheduleList.get(0);
			}

			String courseTime = "待与教练沟通确认";
			if (courseSchedule != null) {
				// 檬营
				if (orderInfo.getOrderType() == OrderType.fun_camp.getIndex()) {
					/**
					 * modify by earvin if
					 * (!Strings.isNullOrEmpty(courseSchedule.getWeekly())) {
					 * StringBuffer strWeekly = new StringBuffer("每周"); /**
					 * String[] weekly = courseSchedule.getWeekly().split(",");
					 * for (String week : weekly) {
					 * strWeekly.append(DateUtil.numToUpper(Integer.parseInt(week)));
					 * } courseTime =
					 * DateUtil.formatDate(courseSchedule.getStartTime(),
					 * DateUtil.FMT_DATE_MMDD) + "至" +
					 * DateUtil.formatDate(courseSchedule.getEndTime(),
					 * DateUtil.FMT_DATE_MMDD) + strWeekly.toString(); } else {
					 * courseTime =
					 * DateUtil.formatDate(courseSchedule.getStartTime(),
					 * DateUtil.FMT_DATE_MMDD) + "至" +
					 * DateUtil.formatDate(courseSchedule.getEndTime(),
					 * DateUtil.FMT_DATE_MMDD); }
					 */

					CourseInfo courseInfo = courseInfoMapper.selectById(servicePrice.getCourseId());
					if (courseInfo != null) {
						courseTime = courseInfo.getStartEndTime();
					} else {
						courseTime = "";
					}

				} else {
					Date startTime = courseSchedule.getStartTime();
					Date endTime = DateUtil.addMinites(startTime, courseSchedule.getDuration());
					courseTime = DateUtils.format(startTime, DateUtils.shortDatePattern) + " "
							+ DateUtils.format(startTime, DateUtils.shortTimePattern) + "～"
							+ DateUtils.format(endTime, DateUtils.shortTimePattern);
				}
			}
			map.put("orderTime", courseTime);
		}

		return map;
	}

	/**
	 * 取消订单
	 * 
	 * @param orderId
	 * @param courseId
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean cancelOrder(int orderId, int courseId) throws Exception {

		log.info("==========cancelOrder start==========");
		log.info("CancelOrder method params is : " + " orderId: " + orderId + " courseId: " + courseId);

		// 查询订单信息
		boolean result = true;
		// OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
		OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);

		// 正常和排队的订单之外的订单不能取消。
		if (!StringUtil.isEquals(OrderContants.OrderStatus.WAIT.getStatus(), orderInfo.getOrderStatus())
				&& !StringUtil.isEquals(OrderContants.OrderStatus.NORMAL.getStatus(), orderInfo.getOrderStatus())) {
			result = false;
			return result;
		}
		String backMoneyFlag = "1";
		if (orderInfo != null) {
			UserInfo userInfo = orderInfo.getUserInfo();
			// 更新订单状态
			String orderType = String.valueOf(orderInfo.getOrderType());
			String orderStatus = orderInfo.getOrderStatus();
			orderInfo.setOrderStatus(OrderContants.OrderStatus.CANCEL.getStatus());
			orderInfo.setCancelAble("1");
			orderInfo.setUpdatedBy(userInfo.getId());
			orderInfo.setUpdatedTime(new Date());
			orderInfo.setCancel(1);
			orderInfo.setUserCancelTime(new Date());
			if (StringUtil.isEquals(OrderContants.OrderType.team_course.getType(), orderType)) {
				orderInfo = cancelTeamCourseOrder(courseId, orderInfo, orderStatus);
			} else if (StringUtil.isEquals(OrderContants.OrderType.fun_camp.getType(), orderType)) {
				// 檬营订单取消
				cancelCampCourseOrder(courseId, orderInfo, orderStatus);
			} else if (StringUtil.isEquals(OrderContants.OrderType.selffit.getType(), orderType)) {
				// 获取相关课程开始的时间
				long startTime = 0L;
				if (orderInfo.getOrderDetail() != null) {
					startTime = orderInfo.getOrderDetail().getStartTime().getTime();
				}
				// 当前时间与课程开始时间六小时之内是不允许退款的，是否退款标志设置为0
				long currentTime = System.currentTimeMillis();
				if (startTime - currentTime > 6 * 60 * 60 * 1000) {
					orderInfo.setCancelBackmoney(1);
				} else {
					orderInfo.setCancelBackmoney(0);
					backMoneyFlag = "0";
				}
			} else {
				return false;
			}
			templateSendService.sendCancelOrderTemplateMsg(String.valueOf(orderInfo.getCancelBackmoney()), orderId);
			// int count =
			// orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
			// 个人储值卡支付 是可退款的
			if (orderInfo.getPayType() == OrderContants.PAY_TYPE_PERSON_ACCOUNT
					&& orderInfo.getCancelBackmoney() == 1) {
				orderInfo.setPayStatus("4");// 表示已退款
			}
			// 企业储值卡支付 是可退款的
			if (orderInfo.getPayType() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT
					&& orderInfo.getCancelBackmoney() == 1) {
				orderInfo.setPayStatus("4");// 表示已退款
				orderRefundToCompanyAccount(orderInfo);
			}
			int count = orderInfoMapper.updateByPrimaryKeyAndVersionSelective(orderInfo);
			// 退款
			OrderRefundToUserAccount(orderInfo.getId());
			if (count > 0) {
				result = true;
			}

		}
		log.info("==========cancelOrder end==========");
		return result;
	}

	/**
	 * 檬营订单取消
	 * 
	 * @param courseId
	 *            课程ID
	 * @param orderInfo
	 *            订单信息
	 * @param orderStatus
	 *            订单状态
	 */
	private void cancelCampCourseOrder(int courseId, OrderInfoResultModel orderInfo, String orderStatus)
			throws OrderException {

		log.info("API---檬营订单取消开始--------->>");
		CourseInfoModel campCourse = courseInfoMapper.queryCampCourseById(courseId);
		int orderPerson = orderInfo.getOrderDetail().getPersonCount() == null ? 0
				: orderInfo.getOrderDetail().getPersonCount();
		int currentCount = campCourse.getCurrentCount() == null ? 0 : campCourse.getCurrentCount();
		log.info("API-檬营订单取消前 当前课程购买人数==>" + currentCount);
		log.info("API-檬营订单取消前 购买人数==>" + orderPerson);
		int waitCount = campCourse.getWaitCount() == null ? 0 : campCourse.getWaitCount();

		if (StringUtil.isEquals(OrderContants.OrderStatus.WAIT.getStatus(), orderStatus)) {
			// 排队订单 退款
			orderInfo.setCancelBackmoney(1);
			
			waitCount = waitCount - orderPerson;
		} else if (StringUtil.isEquals(OrderContants.OrderStatus.NORMAL.getStatus(), orderStatus)) {
			// 当前订单人数减少
			currentCount -= orderPerson;
			log.info("API-当前订单人数减少后的购买人数==>" + currentCount);

			// 正常订单 分 未成营/成营2种状态订单未成营直接取消 成营48小时才 才标记退款
			if (System.currentTimeMillis() < campCourse.getDeadline().getTime()
					&& campCourse.getCurrentCount() < campCourse.getMinCount()) {
				// 未成营订单 退款
				orderInfo.setCancelBackmoney(1);
				// 企业储值卡支付 是可退款的
				if (orderInfo.getPayType() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT
						&& orderInfo.getCancelBackmoney() == 1) {
					orderInfo.setPayStatus("4");// 表示已退款
					orderRefundToCompanyAccount(orderInfo);
				}
			} else if (campCourse.getStartTime().getTime() - System.currentTimeMillis() > 48 * 60 * 60 * 1000) {
				// 已成营订单 确认开始时间大于当前时间48小时 可以退款
				orderInfo.setCancelBackmoney(1);
			} else {
				// 小于48小时 不可退款
				orderInfo.setCancelBackmoney(0);
			}

			// 查询所有排队的订单
			List<OrderInfoResultModel> waitOrders = orderInfoResultMapper
					.selectWaitOrderByServiceId(orderInfo.getServiceId());
			if (waitOrders != null && waitOrders.size() > 0) {
				int personCount = 0;
				for (OrderInfoResultModel waitOrder : waitOrders) {
					int curOrderPersionCount = waitOrder.getOrderDetail().getPersonCount() == null ? 0
							: waitOrder.getOrderDetail().getPersonCount();
					personCount += curOrderPersionCount;
					// 当前课程的人数应该增加
					currentCount += curOrderPersionCount;
					waitCount -= curOrderPersionCount;

					// 将排队等待的订单更新成预订成功
					waitOrder.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
					waitOrder.setUpdatedBy(-1);
					waitOrder.setUpdatedTime(new Date());
					int updateCount = orderInfoMapper.updateByPrimaryKeyAndVersionSelective(waitOrder);
					if (updateCount > 1) {
						throw new RuntimeException("API-排队订单更新错误---->更新到" + updateCount + "条订单数据");
					}
					templateSendService.sendBookingSuccTemplateMsg(waitOrder.getId(), OrderContants.OrderStatus.WAIT.getStatus());
					if (personCount >= orderPerson) {
						break;
					}
				}
				log.info("API-檬营订单取消--处理完成排队------->>");
			}
		}
		// 设置课程的当前人数和排队人数
		if (new Date().after(campCourse.getDeadline()) && campCourse.getCurrentCount() >= campCourse.getMinCount()) {
		} else {
			// 设置课程的当前人数
			campCourse.setCurrentCount(currentCount);
		}

		log.info("API-檬营订单取消后 当前购买 人数====> " + currentCount);
		log.info("API-檬营订单取消后 当前等待 人数====> " + waitCount);
		campCourse.setWaitCount(waitCount);
		int updateCount = courseInfoMapper.updateSelectiveById(campCourse);//.updateByPrimaryKeyAndVersionSelective(campCourse);
		if (updateCount > 1) {
			throw new RuntimeException("API-檬营订单取消更新错误---->更新到" + updateCount + "条课程数据");
		}
		log.info("API-檬营订单取消完成--------->>");
	}

	/**
	 * 团课订单取消
	 * 
	 * @param courseId
	 * @param orderInfo
	 * @param orderStatus
	 */
	private OrderInfoResultModel cancelTeamCourseOrder(int courseId, OrderInfoResultModel orderInfo,
			String orderStatus) {
		CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
		int orderPerson = orderInfo.getOrderDetail().getPersonCount() == null ? 0
				: orderInfo.getOrderDetail().getPersonCount();
		int currentCount = courseInfo.getCurrentCount() == null ? 0 : courseInfo.getCurrentCount();
		int waitCount = courseInfo.getWaitCount() == null ? 0 : courseInfo.getWaitCount();
		log.info("orderPerson :" + orderPerson + "currentCount :" + currentCount + " waitCount :" + waitCount);
		// 排队订单
		if (StringUtil.isEquals(OrderContants.OrderStatus.WAIT.getStatus(), orderStatus)) {
			waitCount = waitCount - orderPerson;
			// 排队中的订单，是允许退款的
			orderInfo.setCancelBackmoney(1);
			// 企业储值卡支付 是可退款的
			if (orderInfo.getPayType() == OrderContants.PAY_TYPE_COMPANY_ACCOUNT
					&& orderInfo.getCancelBackmoney() == 1) {
				orderInfo.setPayStatus("4");// 表示已退款
				orderRefundToCompanyAccount(orderInfo);
			}
		} else if (StringUtil.isEquals(OrderContants.OrderStatus.NORMAL.getStatus(), orderStatus)) {
			currentCount = currentCount - orderPerson;
//			CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//			courseScheduleExample.or().andCourseIdEqualTo(courseId);
//			List<CourseSchedule> courseSchedules = courseScheduleMapper.selectByExample(courseScheduleExample);

            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(courseId);
            EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> courseSchedules = courseScheduleMapper.selectList(entityWrapper);
			// 获取相关课程开始的时间
			long startTime = 0L;
			if (courseSchedules != null && courseSchedules.size() > 0) {
				startTime = courseSchedules.get(0).getStartTime().getTime();
			}
			// 当前时间与课程开始时间六小时之内是不允许退款的，是否退款标志设置为0
			long currentTime = System.currentTimeMillis();
			if (startTime - currentTime > 24 * 60 * 60 * 1000) {
				orderInfo.setCancelBackmoney(1);
			} else {
				orderInfo.setCancelBackmoney(0);
			}
			// 查询所有排队的订单
			List<OrderInfoResultModel> waitOrders = orderInfoResultMapper
					.selectWaitOrderByServiceId(orderInfo.getServiceId());
			if (waitOrders != null && waitOrders.size() > 0) {
				int personCount = 0;
				for (OrderInfoResultModel waitOrder : waitOrders) {
					// 当前订单人数
					int curOrderPersonCount = (waitOrder.getOrderDetail().getPersonCount() == null ? 0
							: waitOrder.getOrderDetail().getPersonCount());
					personCount += curOrderPersonCount;
					// 当前课程的人数应该增加
					currentCount = currentCount + curOrderPersonCount;
					waitCount -= curOrderPersonCount;
					// 将排队等待的订单更新成预订成功
					waitOrder.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
					waitOrder.setUpdatedBy(-1);
					waitOrder.setUpdatedTime(new Date());
					orderInfoMapper.updateSelectiveById(waitOrder);
					templateSendService.sendBookingSuccTemplateMsg(waitOrder.getId(), OrderContants.OrderStatus.WAIT.getStatus());
					if (personCount >= orderPerson) {
						break;
					}
				}
			}
		}
		// 设置课程的当前人数和排队人数
		courseInfo.setCurrentCount(currentCount);
		courseInfo.setWaitCount(waitCount);
		courseInfoMapper.updateSelectiveById(courseInfo);
		return orderInfo;
	}

	/**
	 * 查询用户已完成课时 /时长
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public OrderFinished queryUserLeasonsCount(Integer userId) {

		return orderInfoMapper.queryUserFinishedCourseCount(userId);
	}

	/**
	 * 查询教练已完成课时 /时长
	 *
	 * @param mobile
	 *            教练手机
	 * @return
	 */
	@Override
	public OrderFinished queryCoachFinishedCourseCount(String mobile) {

		return orderInfoMapper.queryCoachFinishedCourseCount(mobile);
	}

	/**
	 * 这里的退款方法是为了用户使用储值卡支付的</br>
	 * 订单在用户取消订单的时候就是直接退款不走管理后台的人工退款</br>
	 * 
	 * @param id
	 */
	public void OrderRefundToUserAccount(int id) {
		OrderInfo orderInfo = orderInfoMapper.selectById(id);
		log.info("================= order status  cancel_backmoney :" + orderInfo.getCancelBackmoney() + "==========");
		UserInfo userInfo = userInfoMapper.selectById(orderInfo.getUserId());
		// 可退款 储值卡支付订单
		if (orderInfo.getCancelBackmoney() == 1 && orderInfo.getPayType() == OrderContants.PAY_TYPE_PERSON_ACCOUNT) {
			OrderRefund orderRefund = new OrderRefund();
			orderRefund.setOrderId(orderInfo.getId());
			orderRefund.setRefundType(OrderContants.PAY_TYPE_PERSON_ACCOUNT);
			orderRefund.setRefundNo(orderInfo.getTradeNo());
			orderRefund.setRefundFee(orderInfo.getAmount().doubleValue());
			orderRefund.setTotalFee(orderInfo.getAmount().doubleValue());
			orderRefund.setRefundStatus("success");// 这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
			orderRefund.setUserId(orderInfo.getUserId());
			orderRefund.setRefundChanne("original");
			orderRefund.setRefundFashion("1");
			orderRefund.setCreatedTime(new Date());
			orderRefund.setCreatedBy(String.valueOf(orderInfo.getUserId()));
			orderRefund.setRemark("储值卡取消直接退款");
			int zhunatai = orderInfoMapper.createdRefundOrder(orderRefund);
			log.info("============== userAccount Refund zhunatai:" + zhunatai + "=======================");
			BigDecimal accountAmt = userInfo.getAccountAmt().add(orderInfo.getAmount());
			userInfo.setAccountAmt(accountAmt);
			int bool = userInfoMapper.updateSelectiveById(userInfo);
			log.info("============== update user accountAmt bool:" + bool + "=======================");
			log.info("============== insert userAccountConsume data =======================");
			// 向储值卡消费记录中添加一条记录
			BigDecimal userAccount = new BigDecimal(-1);
			UserAccountConsume userAccountConsume = new UserAccountConsume();
			userAccountConsume.setUserId(orderInfo.getUserId());
			userAccountConsume.setConsumeType(String.valueOf(1));
			userAccountConsume.setConsumeAmt(userAccount.multiply(orderInfo.getAmount()));
			userAccountConsume.setOrderId(orderInfo.getId());
			userAccountConsume.setRemark("用户取消订单插入数据");
			userAccountConsume.setCreateTime(new Date());
			userAccountConsumeMapper.insert(userAccountConsume);
		}

	}

	/**
	 * 企业订单支付退款
	 *
	 * @param orderInfo
	 *            订单信息
	 * @return boolean true 退款成功/ false 退款失败
	 */
	public boolean orderRefundToCompanyAccount(OrderInfo orderInfo) {

		CompanyStaffConsume companyStaffConsumeQuery = new CompanyStaffConsume();
		companyStaffConsumeQuery.setOrderId(orderInfo.getId());
		//companyStaffConsumeQuery.setOrderStatus(Integer.valueOf(orderInfo.getOrderStatus())); add timo 2017-08-14
		CompanyStaffConsume companyStaffConsume = companyStaffConsumeMapper.selectOne(companyStaffConsumeQuery);

		if (companyStaffConsume != null && companyStaffConsume.getId() != null) {
			companyStaffConsume.setId(null);
			companyStaffConsume.setPayTime(null);
			companyStaffConsume.setCancelTime(new Date());
			companyStaffConsume.setOrderStatus(OrderContants.OrderStatus.CANCEL.getIndex());
		}
		OrderRefund orderRefund = new OrderRefund();
		orderRefund.setOrderId(orderInfo.getId());
		orderRefund.setRefundType(OrderContants.PAY_TYPE_COMPANY_ACCOUNT);
		orderRefund.setRefundNo(orderInfo.getTradeNo());
		orderRefund.setRefundFee(orderInfo.getAmount().doubleValue());
		orderRefund.setTotalFee(orderInfo.getAmount().doubleValue());
		orderRefund.setRefundStatus("success");// 这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
		orderRefund.setUserId(orderInfo.getUserId());
		orderRefund.setRefundChanne("original");
		orderRefund.setRefundFashion("1");
		orderRefund.setCreatedTime(new Date());
		orderRefund.setCreatedBy(String.valueOf(orderInfo.getUserId()));
		orderRefund.setRemark("企业储值卡取消直接退款");
		boolean refound = orderInfoMapper.createdRefundOrder(orderRefund) > 0;
		log.info("企业支付退款结果====? " + refound);

		return companyStaffConsumeMapper.insertSelective(companyStaffConsume) > 0;
	}

	/**
	 * 判断该订单是否可以退款 cancelBackmoney:1(可退款) ,0(不可退款)
	 * 
	 */
	@Override
	public Map<String, Object> ifRefund(int orderId, int courseId) {
		OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
//		CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//		courseScheduleExample.or().andCourseIdEqualTo(courseId);
//		List<CourseSchedule> courseSchedules = courseScheduleMapper.selectByExample(courseScheduleExample);

        CourseSchedule courseScheduleDB = new CourseSchedule();
        courseScheduleDB.setCourseId(courseId);
        EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
        List<CourseSchedule> courseSchedules = courseScheduleMapper.selectList(entityWrapper);
		Map<String, Object> map = new HashMap<>();
		// 正常和排队的订单之外的订单不能取消。
		if (!StringUtil.isEquals(OrderContants.OrderStatus.WAIT.getStatus(), orderInfo.getOrderStatus())
				&& !StringUtil.isEquals(OrderContants.OrderStatus.NORMAL.getStatus(), orderInfo.getOrderStatus())) {
			map.put("cancelBackmoney", 0);
			map.put("rmsg", "正常和排队的订单之外的订单不能取消。");
		}
		String orderType = String.valueOf(orderInfo.getOrderType());
		// 团课订单
		if (OrderContants.OrderType.team_course.getType().equals(orderType)) {
			// 排队的订单是可以退款
			if (OrderContants.OrderStatus.WAIT.getStatus().equals(orderInfo.getOrderStatus())) {
				map.put("cancelBackmoney", 1);
			} else if (OrderContants.OrderStatus.NORMAL.getStatus().equals(orderInfo.getOrderStatus())) {
				// 判断是否在6个小时之内
				long startTime = 0L;
				if (courseSchedules != null && courseSchedules.size() > 0) {
					startTime = courseSchedules.get(0).getStartTime().getTime();
				}
				// 当前时间与课程开始时间六小时之内是不允许退款的，是否退款标志设置为0
				long currentTime = System.currentTimeMillis();
				if (startTime - currentTime > 24 * 60 * 60 * 1000) {
					map.put("cancelBackmoney", 1);
				} else {
					map.put("cancelBackmoney", 0);

				}
			}

		}
		// 檬营订单取消
		else if (StringUtil.isEquals(OrderContants.OrderType.fun_camp.getType(), orderType)) {
			CourseInfoModel campCourse = courseInfoMapper.queryCampCourseById(courseId);
			if (OrderContants.OrderStatus.WAIT.getStatus().equals(orderInfo.getOrderStatus())) {
				// 排队订单 退款
				map.put("cancelBackmoney", 1);
			} else if (OrderContants.OrderStatus.NORMAL.getStatus().equals(orderInfo.getOrderStatus())) {
				// 正常订单 分 未成营/成营2种状态订单未成营直接取消 成营48小时才 才标记退款
				if (System.currentTimeMillis() < campCourse.getDeadline().getTime()
						&& campCourse.getCurrentCount() < campCourse.getMinCount()) {
					// 未成营订单 退款
					map.put("cancelBackmoney", 1);
				} else if (campCourse.getStartTime().getTime() - System.currentTimeMillis() > 48 * 60 * 60 * 1000) {
					// 已成营订单 确认开始时间大于当前时间48小时 可以退款
					map.put("cancelBackmoney", 1);
				} else {
					// 小于48小时 不可退款
					map.put("cancelBackmoney", 0);
				}
			}
		}
		// 自助健身
		else if (StringUtil.isEquals(OrderContants.OrderType.selffit.getType(), orderType)) {
			// 获取相关课程开始的时间
			long startTime = 0L;
			if (orderInfo.getOrderDetail() != null) {
				startTime = orderInfo.getOrderDetail().getStartTime().getTime();
			}
			// 当前时间与课程开始时间六小时之内是不允许退款的，是否退款标志设置为0
			long currentTime = System.currentTimeMillis();
			if (startTime - currentTime > 6 * 60 * 60 * 1000) {
				map.put("cancelBackmoney", 1);
			} else {
				map.put("cancelBackmoney", 0);
			}
		}
		map.put("orderType", orderInfo.getOrderType());
		return map;
	}

	/**
	 * 判断用户是否有预定改课程的订单
	 */
	@Override
	public boolean isBookCourseForUser(int courseId, int userId) {
		Integer count = orderInfoMapper.queryOrderByCourseIdAndUserId(userId, courseId);
		return count > 0;
	}


	/**
	 * 支付方式判断流程
	 * @return
	 */
	public Map<String,Object> checkPayOrderType(UserInfo userInfo,int courseId,int serviceType,int storeId,Date selfTime){
		log.info("-----------checkPayTypeStart-------------------");
		log.info("info ------------>>>>>>  userInfo = "  + userInfo +"courseId "+ courseId +"serviceType "+ serviceType + "storeId "+ storeId +"selfTime "+ selfTime);
		Map<String,Object> respMap = new HashMap<>();

		List<OrderBookTypeModel> payTypeList = new ArrayList<OrderBookTypeModel>();
		ServicePriceResultModel servicePriceResultModel = this.queryServicePriceResultBy(serviceType, storeId,courseId);

		BigDecimal mealCouponPrice = ServiceConstans.defaultMealCouponPrice;
		BigDecimal ptCoursePrice = ServiceConstans.defaultPtCoursePrice;

		BigDecimal primePrice = servicePriceResultModel.getPrimePrice();
		BigDecimal price = servicePriceResultModel.getPrice();
		respMap.put("serviceId", servicePriceResultModel.getServiceId());// 将serviceId 传到前端 
		
		// 判断该用户是否拥有年卡
		UserProductService userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(userInfo.getId(), UserProductServiceConstants.SELFTYPESERVICE);
		if(userProductService != null && userProductService.getIsvalid() == UserProductServiceConstants.ISVALID) {
			respMap.put("hasYearCardService",true); // 拥有年卡身份
        	
    	}else {
    		respMap.put("hasYearCardService",false); // 未拥有年卡
    	}
		
		// 查询该用户是否购买过此课程的订单
        Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(courseId, userInfo.getId(), serviceType);
        respMap.put("hasCourseOrder", hasCourseOrder > 0);
        
		if(userInfo != null){
			int maxPer = 3;
			int minPer =1;

			BigDecimal personMoneyAmount = userInfo.getAccountAmt();
			
			//团课和檬营支付方式及金额判断
			if(serviceType == 1 || serviceType ==3){
				
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
						primePrice, price, primePrice,BigDecimal.ZERO,ptCoursePrice, true, personMoneyAmount, "",true, null));
				
			}else if(serviceType == 2){
				// 私教
				// 私教课程需要判断是否是含有年卡的私教
				CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
				if(courseInfo != null && courseInfo.getProductServiceDetailId() != null && courseInfo.getProductServiceDetailId() > 0) {
					respMap.put("hasYearCardService",true); // 这里给一个拥有年卡的身份
					respMap.put("hasCourseOrder", false); // 该课程是可以重复购买的
				}
				
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, false,
						primePrice, price, primePrice,mealCouponPrice,ptCoursePrice, true, personMoneyAmount, "",true, null));
			}else if(serviceType == 4){
				boolean hasBookSelfOrder = false;
				if (selfTime == null) {
					// 自助时间为空直接返回
					respMap.put("msg", "自助健身开始时间不能为空");
					return respMap;
				}
				//是否已以会员价预约当前时间段的自助健身
				//查询当前时间是否已经预约过 217-03-17 12:00
				hasBookSelfOrder = orderInfoMapper.queryOrderInfoBySelfTime(userInfo.getId(), storeId, selfTime) > 0;

				respMap.put("hasBookSelfOrder", hasBookSelfOrder);
				respMap.put("hasCourseOrder", hasBookSelfOrder);
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, false,
						primePrice, price, primePrice, BigDecimal.ZERO,ptCoursePrice,true, personMoneyAmount, "",true, null));
				
			}else if(serviceType == OrderContants.OrderType.physical_examination.getIndex()) {
				
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
						primePrice, price, primePrice,BigDecimal.ZERO, ptCoursePrice,true, personMoneyAmount, "",true, null));
				
			}else if(serviceType == OrderContants.OrderType.secret_experience.getIndex()) {
				
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
						primePrice, price, primePrice,BigDecimal.ZERO ,ptCoursePrice,true, personMoneyAmount, "",true, null));
				
			}else if(serviceType == OrderContants.OrderType.private_bespeak.getIndex()) {
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
						BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,BigDecimal.ZERO, ptCoursePrice,true, personMoneyAmount, "",true, null));
				
			}
			
			
		}

		respMap.put("payTypeList", payTypeList);

		return respMap;
	}

	/**
	 * 校验下单方式 //bookPriceType:1:原价购买 2：会员价购买 //payType:0：不限制支付方式 ；1在线微信支付； 2:
	 * 用户虚拟账户支付； 3: 企业储值卡支付； 4：微信+个人储值卡混合支付 //personCountType:personCountType
	 * 1:单人 2：多人

	@Override
	public Map<String, Object> checkPayOrderType(UserInfo userInfo, int courseId, int serviceType, int storeId, Date selfTime) {
		log.info("info -----------------------------------------------------------------------------");
		log.info("info ------------>>>>>>  userInfo = "  + userInfo +"courseId "+ courseId +"serviceType "+ serviceType + "storeId "+ storeId +"selfTime "+ selfTime);
		Map<String, Object> respMap = new HashMap<String, Object>();
		// 会员 用户
		List<OrderBookTypeModel> payTypeList = new ArrayList<OrderBookTypeModel>();

		ServicePriceResultModel servicePriceResultModel = this.queryServicePriceResultBy(serviceType, storeId,courseId);

		// 原价
		BigDecimal primePrice = servicePriceResultModel.getPrimePrice();
		// 会员价
		BigDecimal price = servicePriceResultModel.getPrice();

		//BigDecimal finalPrice = primePrice;

		respMap.put("serviceId",servicePriceResultModel.getServiceId());
		
		// 是否支持企业储值卡企业储值卡员工
		Map<String, CompanyStaff> map = new HashMap<String, CompanyStaff>();
		map = this.hasCompanyStaff(userInfo.getId(), serviceType,storeId);
		CompanyStaff companyStaff = map.get("companyAccountAmount");
		if (userInfo != null) {
			//个人代金卡余额
			BigDecimal personMoneyAmount = userInfo.getAccountAmt();
			int maxPer = 3;
			int minPer =1;
			if (serviceType == 1 || serviceType == 3) {
				//是否以企业储值卡会员价购买过该课程
				boolean isBookCourseForCompany = (orderInfoMapper.queryVipOrderByUserIdAndCourseId(userInfo.getId(),courseId,1)  > 0);
				// 是否预以会员身份预定过该课程
				boolean isBookCourseForVip = (orderInfoMapper.queryVipOrderByUserIdAndCourseId(userInfo.getId(),courseId,0)   >  0);
				// 课程价格信息：原价是多少，会员价是多少
				// (1)是企业储值卡用户
				if (companyStaff != null) {
					// (1.1)企业用户，会员
					if (userInfo.getLevel() != null && userInfo.getLevel().intValue() == 2) {
						//是否支持储值卡以会员价购买，判断是否有门店及课程限制
						if (this.hasLimitCompanyCardUsed(companyStaff, storeId, serviceType)) {
							//企业支持多次购买
							if (companyStaff.getVipCheckVipPriceOrderMany() == 1) {
								payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, true,
										price, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
								// 是否支持购买多次
								if (isBookCourseForVip) {
									// 购买过该课程
									// 支付方式 企业支付 价格：会员 人数：多人							
									// 支付方式 非企业支付 价格：原价 人数：多人
									//支付方式，个人储值卡支付
									//finalPrice=primePrice;
								    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
												primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
									//支付方式：微信支付
									payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
											primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
									respMap.put("payTypeNum", 1);
								} else {
									// 未购买过该课程
									// 支付方式 企业支付 价格：会员 人数：多
									// 支付方式 非企业支付 价格：会员 人数：1
									 respMap.put("payTypeNum", 2);
									 payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, false,
											 price, price, primePrice, false, personMoneyAmount, "", false, null));
									//支付方式：微信支付
									 payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, false,
											 price, price, primePrice, false, personMoneyAmount, "", false, null));
								}
							} else {
								// 不支持多次购买
								//是否以企业储值卡会员价购买过课程
								if (isBookCourseForCompany) {
									//以VIP购买过该课程
									if(isBookCourseForVip){
										//混合支付：原价购买 多人
										 respMap.put("payTypeNum", 11);
										 payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
												 primePrice, price, primePrice, true, personMoneyAmount, "", true, null));
										//支付方式：微信支付
										 payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
												 primePrice, price, primePrice, true, personMoneyAmount, "", false, null));
										
									}else{
										//混合支付：会员价  1人
										respMap.put("payTypeNum", 10);
										//支付方式，个人储值卡支付
										//finalPrice=primePrice;
									    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
									    		price, price, primePrice, false, personMoneyAmount, "", true, null));
										//支付方式：微信支付
										payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
												price, price, primePrice, false, personMoneyAmount, "", false, null));
										
									}
									
								} else {
									// 未以企业会员价购买过该课程
									// 支付方式:企业支付 价格：会员价格 人数 1
									// 支付方式：混合支付 价格：会员价格 人数 1
									if(isBookCourseForVip){
										//以会员身份购买过该课程
										respMap.put("payTypeNum", 12);
										//企业支付： 会员    1人
										payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, minPer, true,
												price, price, primePrice, false, personMoneyAmount, companyStaff.getCompanyName(), true , companyStaff));
										//储值卡支付： 原价  多人
										 payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
												 primePrice, price, primePrice, true, personMoneyAmount, "", false, null));
										//支付方式：微信支付 原价  多人
										 payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
												 primePrice, price, primePrice, true, personMoneyAmount, "", false, null));
									}else{
										//未以会员身份会员价购买过该课程
										respMap.put("payTypeNum", 4);
										//企业支付： 会员    1人
										payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, minPer, true,
												price, price, primePrice, false, personMoneyAmount, companyStaff.getCompanyName(), true , companyStaff));
										//非企业支付  会员价  1人
									   payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
									    		price, price, primePrice, false, personMoneyAmount, "", false, null));
										//支付方式：微信支付
										payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
												price, price, primePrice, false, personMoneyAmount, "", false, null));
										
									}
								}
							}

						} else {
							// 企业储值卡+会员用户不支持原价购买
							if (isBookCourseForVip) {
								// 以优惠价购买过该课程
								// 支付方式：企业支付 价格：原价 购买人数 ：多人
								// 支付方式：混合支付 价格：原价 购买人数 ：多人
								payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
										primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
								// 支付方式 非企业支付 价格：原价 人数：多人
								//支付方式，个人储值卡支付
								//finalPrice=primePrice;
							    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
							    		primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
								//支付方式：微信支付
								payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
										primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
								
								respMap.put("payTypeNum", 3);

							} else {
								// 未以优惠价购买过该课程
								// 支付方式：企业支付 价格：原价 购买人数 ：多人
								// 非企业支付 ：价格：会员价 购买人数 ：1
								
								payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
										primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),false, companyStaff));
								// 支付方式 非企业支付 价格：原价 人数：多人
								
								//支付方式，个人储值卡支付
								//finalPrice=primePrice;
							    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
							    		price, price, primePrice, false, personMoneyAmount, "",true, null));
								//支付方式：微信支付
								payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
										price, price, primePrice, false, personMoneyAmount, "",false, null));
								
								respMap.put("payTypeNum", 5);
							}
						}
					} else {
						// (1.2)企业用户，普通用户
						// (1.2.1)支持以会员价格买入
						if (this.hasLimitCompanyCardUsed(companyStaff, storeId, serviceType)) {
							if (companyStaff.getVipCheckVipPriceOrderMany() == 1) {
								// 企业支付 : 会员价 多人
								// 非企业支付: 原价 多人
								respMap.put("payTypeNum", 6);
								payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, true,
										price, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
								
								//支付方式，个人储值卡支付
								//finalPrice=primePrice;
							    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
							    		primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
							    
							} else {
								// 购买过该课程
								if (isBookCourseForCompany) {
									// 非企业支付 原价 多人
									respMap.put("payTypeNum", 7);
									//支付方式，个人储值卡支付
									//finalPrice=primePrice;
								    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
								    		primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
									
								} else {
									// 企业支付：会员价 1人
									// 非企业支付： 原价 多人
									respMap.put("payTypeNum", 8);
									payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, minPer, true,
											price, price, primePrice, false, personMoneyAmount, companyStaff.getCompanyName(), true, companyStaff));
									
									//支付方式，个人储值卡支付
									//finalPrice=primePrice;
								    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
								    		primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
								}
							}

						} else {
							// (1.2.2)不支持会员价格买入
							// 支付方式：企业支付 价格：原价 人数：多人
							// 支付方式:混合支付 价格：原价 人数：多人
							respMap.put("payTypeNum", 9);
							
							payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, true,
									primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
							//支付方式，个人储值卡支付
							//finalPrice=primePrice;
						    payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
						    		primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
						}
						//支付方式：微信支付
						payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
								primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
						
					}

				} else {
					// (2)不是企业储值卡用户
					if (userInfo.getLevel() != null && userInfo.getLevel().intValue() == 2) {
						// 不是企业储值卡用户，是会员
						if (isBookCourseForVip) {
							// 支付方式:代金卡 价格：原价 人数：多人
							payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
										primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
							//支付方式：微信支付  价格：原价 人数：多人
							payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
									primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
								
							respMap.put("payTypeNum", 13);
						} else {
							// 支付方式:混合支付 价格：会员原价 人数：1人
							respMap.put("payTypeNum", 14);
							
							payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
										price, price, primePrice, false, personMoneyAmount, "",true, null));
							
							//支付方式：微信支付
							payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
									price, price, primePrice, false, personMoneyAmount, "",false, null));
						}
					} else {
						// 不是企业储值卡用户and不是会员
						// 支付方式:混合支付 价格：原价 人数：多人
						
						// 支付方式:代金卡 价格：原价 人数：多人
						payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
									primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
						//支付方式：微信支付  价格：原价 人数：多人
						payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
								primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
						respMap.put("payTypeNum", 15);
					}
				}
				//如果是团课订单，判断是否有团课包月卡服务
				if (serviceType == 1) {
					//判断这个课程是否有预定过，有预定过不现实团课包月价格
					Map<String, Object> paramMap = new HashMap<>();
					paramMap.put("userId", userInfo.getId());
					paramMap.put("courseId", courseId);
					paramMap.put("storeId", storeId);
					String startDate = DateUtils.format(new Date(), DateUtils.datePattern);
					CourseTeamResultModel courseTeamResultModel = courseInfoMapper.queryCourseTeamResultById(courseId);
					if (courseTeamResultModel != null && courseTeamResultModel.getStartDate() != null) {
						startDate = courseTeamResultModel.getStartDate();
					}
					//查询用户是否拥有该门店团课包月服务
					List<UserProductServiceResultModel> userProductServicesList = userProductServiceMapper.queryUserProductServiceResultBy(paramMap);
					if (userProductServicesList != null && userProductServicesList.size() > 0) {

						boolean hasTeamMonthlySerivce = orderInfoMapper.queryTeamMonthlyOrderInfoCountByUser(paramMap).intValue() == 0 ? true : false;
						// 用户是否用团课包月卡预定过改团课 --未预定
						if (hasTeamMonthlySerivce) {
							//用户上周购买的团课包月课旷课次数是否小于2次
							//用户本周购买的团课包月课的数量是否小于一次
							//旷课规则：由于团课包月用户旷课成本低，为保障各方利益，须对团课包月特设旷课规则：
							// 当周旷课2次及以上的用户，下周只能预约1次。用户的是否旷课的判断条件为：用户是否完成了该课程的教练端签到。
							respMap.put("isTeamCardBooked", "0");
							if (orderInfoMapper.queryKKCnUserMonthlyTeamOrderInfoLastWeek(userInfo.getId(), startDate) < 2 || (orderInfoMapper.queryKKCnUserMonthlyTeamOrderInfoLastWeek(userInfo.getId(), startDate) >= 2
									&& orderInfoMapper.queryCnUserMonthlyTeamOrderInfoThisWeek(userInfo.getId(), startDate).intValue() < 1)) {
									payTypeList = new ArrayList<OrderBookTypeModel>();
									payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
											new BigDecimal(0), price, primePrice, false, personMoneyAmount, "", true, null));
									//拥有团课包月服务
									respMap.put("price_type_code", "3");
							} else {
								respMap.put("isOverKKCount", "1");//超过旷课次数
							}
						} else {
							respMap.put("isTeamCardBooked", "1");//已预约过该课程
						}
					}
				}
			
            } else if (serviceType == 2) {
            	//私教
            	//支付企业支付
            	if (companyStaff != null) {
            		if (userInfo.getLevel() != null && userInfo.getLevel().intValue() == 2) {
            		    //企业 会员
            			if (this.hasLimitCompanyCardUsed(companyStaff, storeId, serviceType)) {
            				//企业支付||会员价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, true,
            						price, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
            				//代金卡||会员价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, true,
                					price, price, primePrice, true, personMoneyAmount, "",false, null));
            				//微信||会员价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, true,
                					price, price, primePrice, true, personMoneyAmount, "",false, null));	
            				respMap.put("payTypeNum", 21);
            			}else{
            				//企业支付||原价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
            						primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),false, companyStaff));
            				//代金卡||会员价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, true,
                					price, price, primePrice, true, personMoneyAmount, "",true, null));
            				//微信||会员价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, true,
                					price, price, primePrice, true, personMoneyAmount, "",false,null));	
            				respMap.put("payTypeNum", 22);
            			}
                	}else{
            		    //企业 非会员
                		if (this.hasLimitCompanyCardUsed(companyStaff, storeId, serviceType)) {
            				//企业支付||会员价||多人
                			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, true,
            						price, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
            				//代金卡||原价||多人
                			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                					primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
            				//微信||原价||多人
                			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                					primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                			respMap.put("payTypeNum", 23);
            			}else{
            				//企业支付||原价||多人
            				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
            						primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(),true, companyStaff));
            				//代金卡||原价||多人
                			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                					primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
            				//微信||原价||多人
                			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                					primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                			respMap.put("payTypeNum", 24);
            			}
                	}
            	}else{
            		//不是企业支付
            		if (userInfo.getLevel() != null && userInfo.getLevel().intValue() == 2) {
                		//代金卡支付 ||会员价||多人 
            			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, true,
            					price, price, primePrice, true, personMoneyAmount, "",true, null));
            			//微信支付||会员价||多人
            			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, true,
            					price, price, primePrice, true, personMoneyAmount, "",false, null));	
            			respMap.put("payTypeNum", 25);
                	}else{
                		//代金卡支付 ||原价||多人 
                		payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                				primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
            			//微信支付||原价||多人
                		payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                				primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                		respMap.put("payTypeNum", 26);
                	}
            	}
            	
			} else if (serviceType == 4) {
				// 自助订单
				boolean isBookSelfOrder = false;
				if (selfTime == null) {
					// 自助时间为空直接返回
					respMap.put("msg", "自助健身开始时间不能为空");
					return respMap;
				}
                //是否已以会员价预约当前时间段的自助健身
                //查询当前时间是否已经预约过 217-03-17 12:00
                isBookSelfOrder = orderInfoMapper.queryOrderInfoBySelfTime(userInfo.getId(), storeId, selfTime) > 0;

                if (userInfo.getLevel() == 1) {
                    //普通用户
                    //是否支持购买自助健身的企业储值卡员工
                    if (companyStaff != null) {
                        //企业用户 普通用户
                        if (companyStaff.getLimitSelfCourse() != null && companyStaff.getLimitSelfCourse() == 1) {
                            //企业 可以购买自助 企业付款只能以原价购买不可以

							//支付方式: 企业  价格：原价 人数：多人
                            payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(), true, companyStaff));

                            // 支付方式: 代金卡 价格：原价 人数：多人
                            payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "", false, null));

                            //支付方式：微信支付 价格：原价 人数：多人
                            payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "", false, null));
                            respMap.put("payTypeNum", 41);
                            respMap.put("payTypeMsg", "企业 普通用户 企业原价 其它原价");

                        } else {
                            //企业不可购买自助

                            //支付方式: 代金卡 价格：原价 人数：多人
                            payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "", false, null));

                            //支付方式：微信支付 价格：原价 人数：多人
                            payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "", false, null));
                            respMap.put("payTypeNum", 41);
                            respMap.put("payTypeMsg", "企业 普通用户 企业不可购买 其它原价");
                        }

                    } else {
                        //非企业 普通用户

                        //支付方式: 代金卡 价格：原价 人数：多人
                    	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
                        //支付方式：微信支付  价格：原价 人数：多人
                    	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                                primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                        respMap.put("payTypeNum", 42);
                        respMap.put("payTypeMsg", " 非企业 普通用户 其它原价");
                    }

                } else if (userInfo.getLevel() == 2) {
                    //会员用户

                    //是否是支付会员价购买自助健身的企业储值卡员工
                    if (companyStaff != null) {
                        //企业用户 会员
                        if (companyStaff.getLimitSelfCourse() != null && companyStaff.getLimitSelfCourse() == 1 ) {
                            //企业 可以购买自助
                            //支持会员价购买自助健身的企业储值卡员工

                            if (isBookSelfOrder) {
                                //已以会员价预约了当前时间段的自助 全部原价

                                //支付方式: 企业  价格：原价 人数：多人
                                payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
                                        primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(), true, companyStaff));

                                //支付方式: 代金卡 价格：原价 人数：多人
                            	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                                            primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                                //支付方式：微信支付  价格：原价 人数：多人
                            	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                                        primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                                respMap.put("payTypeNum", 43);
                                respMap.put("payTypeMsg", " 企业 会员用户 已下过单 企业原价 其它原价");
                            } else {
                                //企业 原价购买自助健身多人多次 代金 微信 会员价 1人

                                //支付方式: 企业  价格：原价 人数：多人
                                payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, maxPer, false,
                                        primePrice, price, primePrice, true, personMoneyAmount, companyStaff.getCompanyName(), true, companyStaff));

                                //支付方式: 代金卡 价格：会员价 人数：1人
                            	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
                                        price, price, primePrice, false, personMoneyAmount, "",false, null));
                                //支付方式：微信支付  价格：会员价 人数：1人
                            	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
                                        price, price, primePrice, false, personMoneyAmount, "",false, null));
                                respMap.put("payTypeNum", 44);
                                respMap.put("payTypeMsg", " 企业 会员用户 未下过单 企业原价 其它会员价1人");
                            }
                        } else  {
                            //企业不可购买自助

                            if (isBookSelfOrder) {
                                //已以会员价预约了当前时间段的自助 全部原价

                                //支付方式: 代金卡 价格：原价 人数：多人
                                payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                                        primePrice, price, primePrice, true, personMoneyAmount, "",false, null));

                                //支付方式：微信支付  价格：原价 人数：多人
                                payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                                        primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                                respMap.put("payTypeNum", 45);
                                respMap.put("payTypeMsg", " 企业 会员用户 已下过单 企业不可购买 其它原价");
                            } else {

                                //支付方式: 代金卡 价格：会员价 人数：1人
                                payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
                                        price, price, primePrice, false, personMoneyAmount, "",false, null));

                                //支付方式：微信支付  价格：会员价 人数：1人
                                payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
                                        price, price, primePrice, false, personMoneyAmount, "",false, null));
                                respMap.put("payTypeNum", 46);
                                respMap.put("payTypeMsg", " 企业 会员用户 未下过单 企业不可购买 其它会员价1人");
                            }
                        }
                    } else {
                        //非企业 会员
                        if (isBookSelfOrder) {
                            //已以会员价预约了当前时间段的自助

                            // 支付方式:代金卡 价格：原价 人数：多人
                        	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
                            respMap.put("isDefaultCheck", true);
                            //支付方式：微信支付  价格：原价 人数：多人
                        	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
                                    primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
                            respMap.put("payTypeNum", 47);
                            respMap.put("payTypeMsg", " 非企业 会员用户 已过下单 其它原价");

                        } else {
                            //未以会员价购买

                            //支付方式: 代金卡 价格: 会员价 1人
                            payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, minPer, true,
                                    price, price, primePrice, false, personMoneyAmount, "",true, null));

                            //支付方式：微信支付  价格：会员价 人数：1人
                        	payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, minPer, true,
                                    price, price, primePrice, false, personMoneyAmount, "",false, null));
                            respMap.put("payTypeNum", 48);
                            respMap.put("payTypeMsg", " 非企业 会员用户 未下过单 其它会员价1人");
                        }
                    }
                }
            }else if(serviceType == ServiceConstans.ServiceType.physicalCoupon.getIndex()
            		|| serviceType == ServiceConstans.ServiceType.privatePhysical.getIndex()){ 
            	//这里暂时不支持企业支付
        		if (userInfo.getLevel() != null && userInfo.getLevel().intValue() == 2) {
            		//代金卡支付 ||会员价||多人 
        			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, true,
        					price, price, primePrice, true, personMoneyAmount, "",true, null));
        			//微信支付||会员价||多人
        			payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, true,
        					price, price, primePrice, true, personMoneyAmount, "",false, null));	
        			respMap.put("payTypeNum", 49);
            	}else{
            		//代金卡支付 ||原价||多人 
            		payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, maxPer, false,
            				primePrice, price, primePrice, true, personMoneyAmount, "",true, null));
        			//微信支付||原价||多人
            		payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, maxPer, false,
            				primePrice, price, primePrice, true, personMoneyAmount, "",false, null));
            		respMap.put("payTypeNum", 50);
            	}
            }
		}
		
		// 将最终的结果排序： 微信支付排第一、 个人储值卡第二 、企业支付第三
		Collections.sort(payTypeList, new Comparator<OrderBookTypeModel>() {
			public int compare(OrderBookTypeModel order1, OrderBookTypeModel order2) {
				if (order1.getPayType() > order2.getPayType()) {
					return 1;
				} else {
					return -1;
				}

			}
		});
		
		// 增加支付金额条件筛选及选择默认支付方式
		payTypeList = this.selectDefaultPayType(companyStaff, payTypeList, userInfo.getAccountAmt());
		respMap.put("payTypeList", payTypeList);
		return respMap;

	}


	//增加支付金额条件筛选选择默认支付方式判断
	private List<OrderBookTypeModel> selectDefaultPayType(CompanyStaff companyStaff,List<OrderBookTypeModel> payTypeList,BigDecimal userCashCardLimitAmt){
		List<OrderBookTypeModel> newPayTypeList = new ArrayList<OrderBookTypeModel>();
		
		boolean isHasCompanyPayType = false;
		boolean isHasCashCardPayType = false;
		// 判断企业支
		for (int i = 0; i < payTypeList.size(); i++) {
			OrderBookTypeModel model = payTypeList.get(i);
			// 如果包含企业支付
			if (model.getPayType() == 3) {
				isHasCompanyPayType = true;
				// 企业是否限制月度总限额 (0限制 1不限)
				if (companyStaff.getCompanyIsMonthlyTotalLimit().compareTo(BigDecimal.valueOf(0)) == 0) {
					if (companyStaff.getCompanyCurrentLeftAmount().compareTo(model.getFinalPrice()) < 0) {
						//payTypeList.remove(model);
						model.setDefaultCheck(false);
						isHasCompanyPayType = false;
					} else {
						// 是否限制员工月度总限额(0限制 1不限)
						if (companyStaff.getIsMonthlyLimit().intValue() == 0) {
							if (companyStaff.getCompanyMonthlyTotalLimit().compareTo(model.getFinalPrice()) < 0) {
								// 企业配额不足
								//payTypeList.remove(model);
								model.setDefaultCheck(false);
								isHasCompanyPayType = false;
							} else {
								if (companyStaff.getCurrentLeftAmount().compareTo(model.getFinalPrice()) < 0) {
									// 本月配额不足支付订单
									//payTypeList.remove(model);
									model.setDefaultCheck(false);
									isHasCompanyPayType = false;
								}
							}
						} else {
							if (companyStaff.getCompanyMonthlyTotalLimit().compareTo(model.getFinalPrice()) < 0) {
								// 企业配额不足
								//payTypeList.remove(model);
								model.setDefaultCheck(false);
								isHasCompanyPayType = false;
							}
						}
					}
					if(isHasCompanyPayType){
						model.setDefaultCheck(true);
					}
				}
			}
			// 如果包含代金卡支付，但是金额为0，则不允许使用代金卡支付
			if (model.getPayType() == 2) {
				isHasCashCardPayType = true;
				if (userCashCardLimitAmt.compareTo(BigDecimal.valueOf(0)) <1) {
					//payTypeList.remove(model);
					model.setDefaultCheck(false);
					isHasCashCardPayType = false;
				}
			}
		}
		//给支付方式赴默认值
		if (isHasCompanyPayType) {
			for (int i = 0; i < payTypeList.size(); i++) {
				OrderBookTypeModel model = payTypeList.get(i);
				if (model.getPayType() == 3) {
					model.setDefaultCheck(true);
				} else {
					model.setDefaultCheck(false);
				}
				newPayTypeList.add(model);
			}

		} else {
			if (isHasCashCardPayType) {
				for (int i = 0; i < payTypeList.size(); i++) {
					OrderBookTypeModel model = payTypeList.get(i);
					if (model.getPayType() == 2) {
						model.setDefaultCheck(true);
					} else {
						model.setDefaultCheck(false);
					}
					
					newPayTypeList.add(model);
				}
			} else {
				for (int i = 0; i < payTypeList.size(); i++) {
					OrderBookTypeModel model = payTypeList.get(i);
					if (model.getPayType() == 1) {
						model.setDefaultCheck(true);
					} else {
						model.setDefaultCheck(false);
					}
					newPayTypeList.add(model);
				}
			}

		}
		return newPayTypeList;
	}
	
	

	/**
	 * 根据该课程的订单类型判断是否企业支持储值卡支付
	 * 
	 * @param userId
	 * @param serviceType
	 * @return
	 */
	private Map<String, CompanyStaff> hasCompanyStaff(int userId, int serviceType, int sotreId) {
		Map<String, CompanyStaff> respMap = new HashMap<String, CompanyStaff>();
		CompanyStaff companyStaff = companyStaffMapper.selectCompanyPaymentDetailByUserId(userId);
		if (companyStaff != null && companyStaff.getStatus() != null && companyStaff.getStatus() == 0) {

			// 是否可以使用企业支付
			boolean usedCompanyPayType = false;
			if (companyStaff.getIsStoreListLimit()!=null && companyStaff.getIsStoreListLimit() == 0) {
				// 限制是否用门店
				if (serviceType == ServiceType.privateCourse.getIndex()) {
					usedCompanyPayType = true;
				} else {
					String[] storeIds = companyStaff.getStoreListLimit().split("#");
					if (storeIds != null && storeIds.length > 0) {
						for (String sId : storeIds) {
							if (sotreId == Integer.valueOf(sId).intValue()) {
								usedCompanyPayType = true;
								break;
							}
						}
					}
				}
			} else {
				// 不限制使用门店
				usedCompanyPayType = true;
			}
			//判断课程限制
			if (usedCompanyPayType) {
				if (companyStaff.getIsBuyTypeLimit() == 0) {
					// 限制购买课程
					// 团课
					if (companyStaff.getLimitTeamCourse() != null && companyStaff.getLimitTeamCourse() != null
							&& companyStaff.getLimitTeamCourse() == 1
							&& serviceType == ServiceType.teamCourse.getIndex()) {
						respMap.put("companyAccountAmount", companyStaff);
					}
					// 私教
					if (companyStaff.getLimitSecretCourse() != null && companyStaff.getLimitSecretCourse() != null
							&& companyStaff.getLimitSecretCourse() == 1
							&& serviceType == ServiceType.privateCourse.getIndex()) {
						respMap.put("companyAccountAmount", companyStaff);
					}
					// 檬营
					if (companyStaff.getLimitCampCourse() != null && companyStaff.getLimitCampCourse() != null
							&& companyStaff.getLimitCampCourse() == 1
							&& serviceType == ServiceType.campCourse.getIndex()) {
						respMap.put("companyAccountAmount", companyStaff);
					}
					// 自助
					if (companyStaff.getLimitSelfCourse() != null && companyStaff.getLimitSelfCourse() != null
							&& companyStaff.getLimitSelfCourse() == 1
							&& serviceType == ServiceType.selfFitness.getIndex()) {
						respMap.put("companyAccountAmount", companyStaff);
					}
				} else if (companyStaff.getIsBuyTypeLimit() == 1) {
					// 不限制购买课程
					respMap.put("companyAccountAmount", companyStaff);
				}
			}
		}
		return respMap;
	}

	private ServicePriceResultModel queryServicePriceResultBy(int serviceType, int storeId, int courseId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if (courseId > 0) {
			paramMap.put("courseId", courseId);
		}
		if (serviceType > 0) {
			paramMap.put("serviceType", serviceType);
		}
		if (storeId > 0) {
			paramMap.put("storeId", storeId);
		}
		return servicePriceMapper.queryServicePriceByMap(paramMap);
	}

	private OrderBookTypeModel getOrderBookTypeModel(String payDes, int payType, int maxPer, boolean isVipPrice,
			BigDecimal finalPrice, BigDecimal price, BigDecimal prePrice,BigDecimal mealCouponPrice,BigDecimal ptCoursePrice, boolean isMore, BigDecimal moneyCount, String companyName, boolean  isDefaultCheck, CompanyStaff companyAccountAmount) {
			OrderBookTypeModel model = new OrderBookTypeModel();
			model.setPayDes(payDes);
			model.setPayType(payType);
			model.setMaxPer(maxPer);
			model.setVipPrice(isVipPrice);
			model.setFinalPrice(finalPrice);
			model.setPrice(price);
			model.setPrePrice(prePrice);
			model.setMore(isMore);
			model.setMoneyCount(moneyCount);
			model.setDefaultCheck(isDefaultCheck);
			model.setMealCouponPrice(mealCouponPrice);
			model.setPtCoursePrice(ptCoursePrice);
			model.setCompanyAccountAmount(companyAccountAmount);
			return model;
	}
	
	// 判断是否支持企业储值卡会员价购买的购买的产品类型和门店:可以使用 true 不可以使用false
	private boolean hasLimitCompanyCardUsed(CompanyStaff companyStaff, int storeId, int serviceType) {
		boolean isLimit = false;
			if (companyStaff.getVipCheckType() == 0) {
				// 是否包含门店限制
				if (companyStaff.getVipCheckStoreLimit() == 0) {
					//私教不判断门店逻辑
					if(serviceType == ServiceType.privateCourse.getIndex()||serviceType == ServiceType.selfFitness.getIndex()){
						isLimit=true;
					}else{
						String[] storeIds = companyStaff.getVipCheckStoreList().split("#");
						if (storeIds != null && storeIds.length > 0) {
							for (String sId : storeIds) {
								if (storeId == Integer.valueOf(sId).intValue()) {
									isLimit = true;
									break;
								}
							}
						}
					}
				} else {
					isLimit = true;
				}
				
				if (isLimit) {
					// 会员价购买课程限制
					if (companyStaff.getVipCheckCourseTypeLimit() == 0) {
						// 团课限制vip_check_course_type_team
						if (serviceType == ServiceType.teamCourse.getIndex()) {
							if (companyStaff.getVipCheckCourseTypeTeam() == 0) {
								isLimit = false;
							}
						} else if (serviceType == ServiceType.privateCourse.getIndex()) {
							if (companyStaff.getVipCheckCourseTypePrivate() == 0) {
								isLimit = false;
							}
						} else if (serviceType == ServiceType.campCourse.getIndex()) {
							if (companyStaff.getVipCheckCourseTypeCamp() == 0) {
								isLimit = false;
							}
						}
					}
				}
			}
        
        return isLimit;
	}
	
	/**
	 * 包月卡支付方式返回判断
	 * 这里因为新业务需求 除了 充值代金卡才能使用微信支付
	 * 其余的订单全部使用储值卡 支付
	 * 判断的条件的代码这里注释暂时保留以便后期的业务需求再次改变
	 * 
	 */
	@Override
	public Map<String, Object> checkPayCarMonthOrderType(UserInfo userInfo, Integer serviceId, Integer productId) {
		ProductServiceDetail productServiceDetail = productServiceDetailMapper.selectById(serviceId);
		List<OrderBookTypeModel> payTypeList = new ArrayList<OrderBookTypeModel>();
		Map<String,Object> respMap = new HashMap<>();
		if(productServiceDetail == null){
			return null;
		}
		respMap.put("hasYearCardService", true);
		respMap.put("hasCourseOrder", false);
		BigDecimal productServicePrice = productServiceDetail.getPdPrimePrice().multiply(BigDecimal.valueOf(productServiceDetail.getPdDiscount())).setScale(2, BigDecimal.ROUND_HALF_UP);
		payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, true, 0, 0,null));
		/*CompanyStaff companyStaff = companyStaffMapper.selectCompanyPaymentDetailByUserId(userInfo.getId());
		if(companyStaff != null){
			// 允许购买会员
			if(companyStaff.getLimitVip() != null && companyStaff.getLimitVip() == 1){
				BigDecimal checkUserHasCompanyPay = BigDecimal.valueOf(10);// 校验用户是否拥有企业支付
				// 企业是否限制月度总限额 (0限制 1不限)
				if(companyStaff.getCompanyIsMonthlyTotalLimit().compareTo(BigDecimal.valueOf(0)) == 0){
					if(companyStaff.getCompanyMonthlyTotalLimit().compareTo(BigDecimal.valueOf(0)) == 0){
						checkUserHasCompanyPay = BigDecimal.valueOf(0);
					}
				}
				// 企业当前余额
				if(companyStaff.getCompanyCurrentLeftAmount().compareTo(BigDecimal.valueOf(0)) == 0){
					checkUserHasCompanyPay = BigDecimal.valueOf(0);
				}
				// 用户每月配额有钱
				if(companyStaff.getMonthlyLimit() != null
						&& checkUserHasCompanyPay.compareTo(BigDecimal.valueOf(0)) > 0
						&& companyStaff.getCurrentLeftAmount().compareTo(BigDecimal.valueOf(0)) > 0){
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, false, 0, 0,null));
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, false, 0, 0,null));
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_COMPANY_ACCOUNT_NAME, OrderContants.PAY_TYPE_COMPANY_ACCOUNT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, true, 0, 0,companyStaff));
				}
			}
		}
		if(payTypeList.size() == 0){
			if(userInfo.getAccountAmt().compareTo(productServicePrice) > 0){
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, false, 0, 0,null));
				payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, true, 0, 0,null));

			}else{
				if(userInfo.getAccountAmt().compareTo(BigDecimal.ZERO) > 0){
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, false, 0, 0,null));
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, true, 0, 0,null));
				}else{
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_WECHAT_NAME, OrderContants.PAY_TYPE_WECHAT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, true, 0, 0,null));
					payTypeList.add(this.getOrderBookTypeModel(OrderContants.PAY_TYPE_PERSON_ACCOUNT_NAME, OrderContants.PAY_TYPE_PERSON_ACCOUNT, 1, false,productServicePrice , productServicePrice, productServiceDetail.getPdPrimePrice(), false, userInfo.getAccountAmt(), null, false, 0, 0,null));
				}
			}
		}*/

		respMap.put("payTypeList", payTypeList);
		return respMap;
	}

	private OrderBookTypeModel getOrderBookTypeModel(String payDes, int payType, int maxPer, boolean isVipPrice,
			BigDecimal finalPrice, BigDecimal price, BigDecimal prePrice, boolean isMore, BigDecimal moneyCount,
			String companyName, boolean  isDefaultCheck, Integer point,Integer userPoint , CompanyStaff companyAccountAmount) {
			OrderBookTypeModel model = new OrderBookTypeModel();
			model.setPayDes(payDes);
			model.setPayType(payType);
			model.setMaxPer(maxPer);
			model.setVipPrice(isVipPrice);
			model.setFinalPrice(finalPrice);
			model.setPrice(price);
			model.setPrePrice(prePrice);
			model.setMore(isMore);
			model.setMoneyCount(moneyCount);
			model.setDefaultCheck(isDefaultCheck);
			model.setCompanyAccountAmount(companyAccountAmount);
			/*model.setPoint(point);
			model.setUserPoint(userPoint);*/
			return model;
	}

	/**
	 * 判断自助健身资源是否紧张
	 * @param storeId
	 * @param startTime
	 * @return
	 */
	@Override
	public Map<String, Object> checkStoreSelfOrderCount(Integer storeId, String startTime) {
		Map<String,Object> respMap = new HashMap<>();
		StoreInfo storeInfo =storeInfoMapper.selectById(storeId);
		Integer storeMaxCount = storeInfo.getMaxCount()==null? 0 :storeInfo.getMaxCount();
		Integer starTimeAreaOrderCount = orderDetailMapper.querySelfOrderCountBy(storeId,startTime);
		Integer storeStartTimeStatus = 1;
		storeStartTimeStatus = starTimeAreaOrderCount / (double)storeMaxCount >= 0.8 ? (starTimeAreaOrderCount / storeMaxCount == 1 ? 3 : 2) : 1;
		respMap.put("storeStartTimeStatus",storeStartTimeStatus);
		respMap.put("storeMaxCount",storeMaxCount);
		return respMap;
	}

	/**
     * 获取用户餐券总和
     */
	@Override
	public int getUserMealCount(Integer userId) {
		return this.orderInfoMapper.queryUserMealCount(userId);
	}

	@Override
	public MealListVO queryMealDetailCount(Integer userId) {
		return this.orderInfoMapper.queryMealDetailCount(userId);
	}

	@Override
	public List<MealListVO> queryMealDetail(Map<String, Integer> param) {
		return this.orderInfoMapper.queryMealDetail(param);
	}

	@Override
	public MealListVO queryMealOrderDetail(Integer orderId) {
		return this.orderInfoMapper.queryMealOrderDetail(orderId);
	}

	@Override
	public List<MealListVO> queryTomrrowMealList(String dateTime) {
		return this.orderInfoMapper.queryTomrrowMealList(dateTime);
	}

	@Override
	public MealListVO queryTomrrowMealSum(String dateTime) {
		return this.orderInfoMapper.queryTomrrowMealSum(dateTime);
	}

	@Override
	public List<MealListVO> queryTomrrowTeamMealList(String dateTime) {
		return this.orderInfoMapper.queryTomrrowTeamMealList(dateTime);
	}

	@Override
	public int queryAllTeamPersonByDay(String dateTime) {
		return this.orderInfoMapper.queryAllTeamPersonByDay(dateTime);
	}

	@Override
	public List<CasherResolveLog> queryCasherLog(Integer casherId, String dateTime) {
		return this.orderInfoMapper.queryCasherLog(casherId, dateTime);
	}

	@Override
	public CasherResolveLog queryCasherSumMoney(Integer casherId, String dateTime) {
		return this.orderInfoMapper.queryCasherSumMoney(casherId, dateTime);
	}
}
